<template>
  <div>
    <n-card :bordered="false">
      <BasicForm
        v-if="searchSchemas"
        @register="registerForm"
        layout="horizontal"
        @submit="handleSearch"
        @reset="handleReset"
      />
    </n-card>
    <n-card :bordered="false" class="mt-3">
      <!--  :columns="columns" -->
      <BasicTable
        :columns="columns"
        :request="loadData"
        :row-key="rowKey"
        :checkable="true"
        ref="tableRef"
        :actionColumn="actionColumn"
        :pagination="paginationConfig"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="scrollX"
        :striped="true"
      >
        <template #tableTitle>
          <n-button v-if="showAddButton" type="primary" @click="handleAdd">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新增
          </n-button>
          <n-button
            v-if="showDeleteButton"
            class="ml-3"
            type="error"
            @click="handleBatchDelete"
            :disabled="!checkedIds.length"
          >
            <template #icon>
              <n-icon>
                <DeleteOutlined />
              </n-icon>
            </template>
            删除
          </n-button>
          <slot name="tableTitle"></slot>
        </template>
        <template #toolbar>
          <slot name="toolbar"></slot>
        </template>
      </BasicTable>

      <n-modal
        v-model:show="showModal"
        :show-icon="false"
        :preset="modalPreset"
        :title="currentModalTitle || modalTitle"
      >
        <n-form
          v-if="formSchemas"
          :model="formModel"
          :rules="formRules"
          ref="formRef"
          label-placement="left"
          :label-width="labelWidth"
          class="py-4"
        >
          <template v-for="schema in formSchemas" :key="schema.field">
            <n-form-item :label="schema.label" :path="schema.field">
              <component
                :is="schema.component"
                v-bind="schema.componentProps"
                v-model:value="formModel[schema.field]"
                :placeholder="schema.placeholder"
              />
            </n-form-item>
          </template>
        </n-form>

        <template #action>
          <n-space>
            <n-button @click="() => (showModal = false)">取消</n-button>
            <n-button type="info" :loading="formBtnLoading" @click="confirmForm"> 确定 </n-button>
          </n-space>
        </template>
      </n-modal>
    </n-card>
  </div>
</template>

<script lang="ts" setup generic="T extends Record<string, any>">
  import { h, reactive, ref, computed, useSlots, onMounted } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { PlusOutlined, DeleteOutlined } from '@vicons/antd';
  import { useMessage } from 'naive-ui';

  // 扩展 FormSchema 接口以支持异步选项
  interface ExtendedFormSchema extends FormSchema {
    asyncOptions?: () => Promise<any[]>; // 异步获取选项的方法
  }

  // 定义组件属性
  interface Props {
    // 表格相关
    columns: any[];
    rowKey: (row: T) => string;
    scrollX?: number;

    // 分页配置
    paginationConfig?: any;

    // 表单相关
    searchSchemas?: FormSchema[];
    formSchemas?: ExtendedFormSchema[];
    formRules?: any;
    labelWidth?: number;

    // 默认初始化加载表格配置
    autoLoad?: boolean;

    // API 方法
    apiMethods: {
      getList: (params: any) => Promise<any>;
      add?: (params: any) => Promise<any>;
      update?: (params: any) => Promise<any>;
      delete?: (params: any) => Promise<any>;
      batchDelete?: (params: any) => Promise<any>;
      validate?: (params: any) => Promise<any>;
    };

    // 显示配置
    showAddButton?: boolean;
    showDeleteButton?: boolean;

    // 标题
    modalTitle?: string;
    modalPreset?: string;
  }

  const props = withDefaults(defineProps<Props>(), {
    scrollX: 1000,
    paginationConfig: () => ({ pageSize: 10 }),
    labelWidth: 100,
    autoLoad: true,
    showAddButton: true,
    showDeleteButton: true,
    modalTitle: '操作',
    modalPreset: 'dialog',
  });

  // 事件定义
  const emit = defineEmits<{
    (e: 'add'): void;
    (e: 'edit', record: T): void;
    (e: 'delete', record: T): void;
    (e: 'batch-delete', ids: string[]): void;
    (e: 'search', values: any): void;
    (e: 'reset', values: any): void;
    (e: 'success', operation: string): void;
    (e: 'error', error: any): void;
  }>();

  // 插槽
  const slots = useSlots();

  // 响应式数据
  const message = useMessage();
  const tableRef = ref();
  const formRef = ref();
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedIds = ref<string[]>([]);
  const formModel = reactive<Record<string, any>>({});
  const currentModalTitle = ref(''); // 动态标题
  const formSchemaOptions = ref<Record<string, any[]>>({}); // 存储异步选项

  // 添加一个状态来控制是否可以加载数据
  const canLoadData = ref(false);

  // 表单注册
  const [registerForm, { getFieldsValue }] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: props.labelWidth,
    schemas: props.searchSchemas || [],
  });

  // 动作列定义
  const actionColumn = computed(() => ({
    width: 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render: (record: T) => {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: () => handleEdit(record),
            ifShow: () => !!props.apiMethods.update,
          },
          {
            label: '删除',
            onClick: () => handleDelete(record),
            ifShow: () => !!props.apiMethods.delete,
          },
        ],
      });
    },
  }));

  // 添加一个响应式变量来存储默认参数
  const defaultParams = ref<Record<string, any>>({});

  // 添加设置默认参数的方法
  function setDefaultParams(params: Record<string, any>) {
    Object.assign(defaultParams.value, params);
  }

  // 修改columns处理逻辑，添加序号列支持
  const processedColumns = computed(() => {
    // 检查是否需要添加序号列（检查columns中是否有key为'id'的列）
    const hasIndexColumn = props.columns.some((column) => column.key === 'id');

    if (hasIndexColumn) {
      // 找到'id'列并替换为序号列
      return props.columns.map((column) => {
        if (column.key === 'id') {
          return {
            ...column,
            title: column.title || '序号',
            key: 'id',
            render: (row: any, index: number) => {
              // 获取当前页码和页面大小计算序号
              const pagination = tableRef.value?.getPaginationRef();
              const currentPage = pagination?.page || 1;
              const pageSize = pagination?.pageSize || 10;
              return (currentPage - 1) * pageSize + index + 1;
            },
          };
        }
        return column;
      });
    }

    return props.columns;
  });

  // 加载异步选项
  async function loadAsyncOptions() {
    const options: Record<string, any[]> = {};
    for (const schema of props.formSchemas || []) {
      const extendedSchema = schema as ExtendedFormSchema;
      if (extendedSchema.asyncOptions) {
        try {
          const data = await extendedSchema.asyncOptions();
          options[extendedSchema.field] = data;
          // 更新组件属性
          if (extendedSchema.componentProps) {
            extendedSchema.componentProps.options = data;
          } else {
            extendedSchema.componentProps = { options: data };
          }
        } catch (error) {
          console.error(`加载字段 ${extendedSchema.field} 的异步选项失败:`, error);
        }
      }
    }
    formSchemaOptions.value = options;
  }

  // 在组件挂载时根据 autoLoad 设置 canLoadData
  onMounted(() => {
    canLoadData.value = props.autoLoad;
  });

  // 添加启用数据加载的方法
  function enableDataLoad() {
    
    canLoadData.value = true;
    // if(!canLoadData.value){
    //   canLoadData.value = true;
    // }
  }

  // 数据加载方法
  const loadData = async (res: any) => {
    // 如果不允许加载数据，则返回空数据
    if (!canLoadData.value) {
      return {
        list: [],
        itemCount: 0,
      };
    }
    try {
      let params = {
        ...defaultParams.value, // 添加默认参数
        ...getFieldsValue(),
        ...res,
        currentPage: res.page,
        pageSize: res.pageSize,
      };

      // 清理空参数
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });

      const response = await props.apiMethods.getList(params);
      const data = response.data || response;
      
      const result = {
        list: data.records || data.list || [],
        itemCount: data.total || data.itemCount || 0,
      };
      return result;
    } catch (error) {
      message.error('数据加载失败: ' + (error.message || '未知错误'));
      return {
        list: [],
        itemCount: 0,
      };
    }
  };

  // 事件处理方法
  function onCheckedRow(rowKeys: string[]) {
    checkedIds.value = rowKeys;
  }

  function reloadTable(params: any = {}) {
    // enableDataLoad();
    tableRef.value?.reload(params);
  }

  async function handleAdd() {
    // 重置表单
    Object.keys(formModel).forEach((key) => {
      formModel[key] = undefined;
    });
    emit('add');
    // 设置新增标题
    currentModalTitle.value = '新增' + (props.modalTitle || '');
    // 加载异步选项
    await loadAsyncOptions();

    showModal.value = true;
  }

  function handleEdit(record: T) {
    // 填充表单数据
    Object.assign(formModel, record);
    emit('edit', record);
    // 设置编辑标题
    currentModalTitle.value = '编辑' + (props.modalTitle || '');
    // 加载异步选项
    loadAsyncOptions();
    showModal.value = true;
  }

  async function handleDelete(record: T) {
    if (!props.apiMethods.delete) {
      message.warning('删除功能未配置');
      return;
    }

    window['$dialog'].info({
      title: '确认删除',
      content: `确定要删除选中的项吗？此操作不可恢复！`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          const result = await props.apiMethods.delete!(record);
          if (result === true || result.code === 0) {
            message.success('删除成功');
            reloadTable();
            emit('success', 'delete');
          } else {
            message.error(result.errMsg || '删除失败');
            emit('error', result.errMsg || '删除失败');
          }
        } catch (error) {
          message.error('删除失败: ' + error.message);
          emit('error', error);
        }
      },
      onNegativeClick: () => {
        message.info('已取消删除');
      },
    });
  }

  async function handleBatchDelete() {
    if (!props.apiMethods.batchDelete) {
      message.warning('批量删除功能未配置');
      return;
    }

    if (!checkedIds.value.length) {
      message.warning('请先选择要删除的项');
      return;
    }

    window['$dialog'].info({
      title: '确认批量删除',
      content: `确定要删除选中的 ${checkedIds.value.length} 项吗？此操作不可恢复！`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          const result = await props.apiMethods.batchDelete!({ ids: checkedIds.value });
          if (result === true || result.code === 0) {
            message.success(`批量删除 ${checkedIds.value.length} 项成功`);
            checkedIds.value = [];
            reloadTable();
            emit('success', 'batch-delete');
          } else {
            message.error(result.errMsg || '批量删除失败');
            emit('error', result.errMsg || '批量删除失败');
          }
        } catch (error) {
          message.error('批量删除失败: ' + error.message);
          emit('error', error);
        }
      },
      onNegativeClick: () => {
        message.info('已取消批量删除');
      },
    });
  }

  async function confirmForm(e: Event) {
    e.preventDefault();
    formBtnLoading.value = true;

    try {
      await formRef.value?.validate();

      const params = { ...formModel };
      // 清理空参数
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });

      let result;
      // 根据是否有ID判断是新增还是编辑
      if (params.id || params[props.rowKey({} as T)]) {
        // 编辑
        if (props.apiMethods.validate) {
          const validateResult = await props.apiMethods.validate(params);
          if (validateResult !== true) {
            message.error('数据验证失败，请检查后重试');
            return;
          }
        }
        if (props.apiMethods.update) {
          result = await props.apiMethods.update(params);
        }
      } else {
        // 新增
        if (props.apiMethods.add) {
          result = await props.apiMethods.add(params);
        }
      }

      if (result === true || (result && result.code === 0)) {
        message.success(params.id ? '编辑成功' : '新增成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
          emit('success', params.id ? 'update' : 'add');
        }, 500);
      } else {
        message.error(result?.errMsg || '操作失败');
        emit('error', result?.errMsg || '操作失败');
      }
    } catch (error) {
      message.error('操作失败: ' + error.message);
      emit('error', error);
    } finally {
      formBtnLoading.value = false;
    }
  }

  function handleSearch(values: any) {
    emit('search', values);
    reloadTable();
  }

  function handleReset(values: any) {
    emit('reset', values);
    reloadTable();
  }

  // 暴露方法给父组件
  defineExpose({
    reload: reloadTable,
    getCheckedIds: () => checkedIds.value,
    setFormModel: (model: Record<string, any>) => Object.assign(formModel, model),
    // 添加获取分页信息的方法
    getPaginationRef: () => tableRef.value?.getPaginationRef?.(),
    // 添加直接访问tableRef的方法
    tableRef: tableRef,
    // 添加启用数据加载的方法
    enableDataLoad,
    // 添加设置默认参数的方法
    setDefaultParams,
  });
</script>
